package com.jk.common.neutronAI;

import com.alibaba.fastjson.JSONObject;
import com.jk.common.neutronAI.dto.ApiChatCompletionRequest;
import com.jk.common.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * Description: NeutronAIApiClient 第三方接口调用
 * Author: 豆子高
 * Date: 2025/2/24 14:26
 */
@Slf4j
@Component
public class NeutronAIApiClient {

    @Value("${neutron.ai.url}")
    private String neutronAIUrl;

    @Value("${neutron.ai.api-key}")
    private String neutronAIKey;


    public String sendPostRequest(String urlStr, String jsonData) throws Exception {
        try {
            log.info("NeutronAIApiClient urlStr: {}, jsonData: {}", urlStr, jsonData);
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Authorization", neutronAIKey);
            conn.setDoOutput(true);

            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonData.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                log.info("NeutronAIApiClient response: {}", response);
                return response.toString();

            } finally {
                conn.disconnect();
            }
        } catch (Exception e) {
            log.error("NeutronAIApiClient error: {}", e.getMessage(), e);
            throw new Exception("NeutronAIApiClient error: " + e.getMessage(), e);
        }
    }

    public ResponseResult neutronChatCompletions(ApiChatCompletionRequest apiChatCompletionRequest) throws Exception {
        try {
            String responseResult = sendPostRequest(neutronAIUrl, JSONObject.toJSONString(apiChatCompletionRequest));
            return JSONObject.parseObject(responseResult,ResponseResult.class);
        } catch (Exception e) {
            throw new Exception("NeutronAIApiClient error: " + e.getMessage(), e);
        }
    }

}
